var http = require("http");
var url = require("url");//url模块
var template = require("art-template");
var fs = require("fs");
const port = 12345;

var server = http.createServer().listen(port,function(){
	console.log("服务已启动,port:"+port);
});
var users = [
	{'id':'1','userName':'张三','birthday':'2019-02-09','age':'23'},
	{'id':'2','userName':'李四','birthday':'1998-03-19','age':'33'}
];
server.on("request",function(req,res){
	//第二个参数 时将query参数转成json对象
	var urlObj = url.parse(req.url,true);
	console.log("url对象:"+urlObj);
	if(urlObj.pathname === "/"){
		fs.readFile("./view/index.html",function(err,data){
			if(err){
				return console.error("读取文件异常",e);
			}
			var html = template.render(data.toString(),{'users':users});
			console.log(html);
			res.end(html);
		});
	}else if(urlObj.pathname.indexOf("/public") == 0){
		fs.readFile("."+urlObj.pathname,function(err,data){
			if(err){
				return console.error("读取文件异常",e);
			}
			res.end(data);
		});
	}else if(urlObj.pathname === "/user/save"){
		var user = {'id':Date.now(),'userName':urlObj.query.userName,'birthday':urlObj.query.birthday,'age':urlObj.query.age}
		users.push(user);
		// 通过响应头来实现服务端重定向
		res.writeHead(302,{
			'Location': '/'
		})
		res.end();
	}else{
		res.end("404");
	}
});